package com.zym.framework.utlis;

import com.zym.application.exception.AppBugExcepiton;
import com.zym.application.utils.LogUtils;
import com.zym.framework.exception.ZymFwExcepiton;
import javafx.fxml.FXMLLoader;

import java.io.IOException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.ResourceBundle;

/**
 * QQ 165149324
 * 臧英明
 *
 * @author
 * @create 2021-02-03
 */
public class FxmlUtil {
    private static final Map<String,FXMLLoader> cacheMap = new HashMap<>();
    public FxmlUtil() {
    }

    public static FXMLLoader loadFxmlFromResource(String resourcePath) {
        return loadFxmlFromResource(resourcePath, (ResourceBundle)null);
    }

    public static FXMLLoader loadFxmlFromResource(String resourcePath, ResourceBundle resourceBundle) {
        try {
            LogUtils.println("加载组件"+resourcePath);
            FXMLLoader fxmlLoader = new FXMLLoader();
            URL resource = FxmlUtil.class.getResource(resourcePath);
            fxmlLoader.setLocation(FxmlUtil.class.getResource(resourcePath));
            fxmlLoader.setResources(resourceBundle);
            fxmlLoader.load();
            cacheMap.put(resourcePath,fxmlLoader);
            return fxmlLoader;
        } catch (IOException var3) {
            var3.printStackTrace();
            throw new ZymFwExcepiton(var3);
        }
    }
    public static FXMLLoader getCacheLoader(String resourcePath){
        return cacheMap.get(resourcePath);
    }
    public static <T> T getCacheController(String resourcePath,Class<T> clazz){
        FXMLLoader cacheLoader = getCacheLoader(resourcePath);
        if(cacheLoader == null){
            throw new AppBugExcepiton("未加载");
        }
        T controller = cacheLoader.getController();
        return controller;
    }
}
